/**This script is the database script.
 * 
 */
/*
var prop_name= $("#property_name").val();
var street = $("#street").val();
var suburb =$("#suburb").val();
var town =$("#town").val();
var district =$("#district").val();
var date =$("#date").val();
var owner_name = $("#owner_name").val();
var introducer =$("#introducer").val();
*/

var dbShell;
var shortName = 'database';
var version ='1.0';
var displayName = 'property database';
var maxSize = 65535;


function dbErrorHandler(err){
    alert("DB Error: "+err.message + "\nCode="+err.code);
}

function phoneReady(){
    doLog("phoneReady");
    //First, open our db
    
    dbShell = window.openDatabase(shortName, version, displayName, maxSize);
    doLog("db was opened");
    //run transaction to create initial tables
    dbShell.transaction(setupTable,dbErrorHandler,getEntries);
    doLog("ran setup");
}

//I just create our initial table - all one of em
function setupTable(tx){
    doLog("before execute sql...");
    tx.executeSql("CREATE TABLE IF NOT EXISTS Property_detail(id INTEGER PRIMARY KEY,property_name TEST NOT NULL, " +
    		"street TEXT, suburb TEXT,town TEXT, district TEXT, date INTEGER, owner_name TEXT, " +
    		"introducer TEXT)");
    doLog("after execute sql...");
}   

//I handle getting entries from the db
function getEntries() {
    
    //doLog("get entries");
    dbShell.transaction(function(tx) {
        tx.executeSql("select property_name,street,suburb,town, district,date,owner_name," +
        		"introducer from Property_detail",[],renderEntries,dbErrorHandler);
    }, dbErrorHandler);
}

    
function renderEntries(tx,results){
    /*doLog("render entries");
    if (results.rows.length == 0) {
        $("#mainContent").html("<p>You currently do not have any props.</p>");
    } else {
       var s = "";
       for(var i=0; i<results.rows.length; i++) {
         s += "<li><a href='edit.html?id="+results.rows.item(i).id + "'>" + results.rows.item(i).title + "</a></li>";   
       }
       $("#propTitleList").html(s);
       $("#propTitleList").listview("refresh");
    }*/
}

function saveprop(data, cb) {
    //Sometimes you may want to jot down something quickly....
    //if(Property_detail.prop_name == "") Property_detail.prop_name = "[No prop_name]";
    dbShell.transaction(function(tx) {
        /*if(Property_detail.id == "")*/ tx.executeSql("insert into Property_detail(property_name,street,suburb,town, district,date,owner_name,introducer) VALUES (?,?,?,?,?,?,?,?)", [property_detail.property_name, property_detail.street, property_detail.suburb, property_detail.town, property_detail.district, property_detail.date, property_detail.woner_name, property_detail.introducer]);
       // else tx.executeSql("update Property_detail set property_name=?, street=?, updated=? where id=?",[prop.title,prop.body, new Date(), prop.id]);
    }, dbErrorHandler,cb);
}

function initDB(){
    document.addEventListener("deviceready", phoneReady, false);
    
    //handle form submission of a new/old prop
   // $("#editpropForm").live("submit",function(e) {
        var data = {prop_name:$("#property_name").val(),
				street : $("#street").val(),
	 			suburb: $("#suburb").val(),
	 			town :$("#town").val(),
	 			district :$("#district").val(),
	 			date : $("#date").val(),
	 			owner_name : $("#owner_name").val(),
	 			introducer : $("#introducer").val()
        };
        saveprop(data,function() {
            $.mobile.changePage("icon-page.html",{reverse:true});
        });
        e.preventDefault();submissionform
    //});

    //will run after initial show - handles regetting the list
    $("#homePage").live("pageshow", function() {
        getEntries(); 
    });

    //edit page logic needs to know to get old record (possible)
  /* $("#detail-page").live("pageshow", function() {
        //get the location - it is a hash - got to be a better way
        var loc = window.location.hash;
        if(loc.indexOf("?") >= 0) {
            var qs = loc.substr(loc.indexOf("?")+1,loc.length);
            var propId = qs.split("=")[1];
            //load the values
            $("#editFormSubmitButton").attr("disabled","disabled"); 
            dbShell.transaction(
                function(tx) {
                    tx.executeSql("select id,title,body from property_detail where id=?",[propId],function(tx,results) {
                        $("#propId").val(results.rows.item(0).id);
                        $("#propTitle").val(results.rows.item(0).title);
                        $("#propBody").val(results.rows.item(0).body);
                        $("#editFormSubmitButton").removeAttr("disabled");   
                    });
                }, dbErrorHandler);
            
        } else {
         $("#editFormSubmitButton").removeAttr("disabled");   
        }
    });*/
}




















/*
var db;
//initialize  database
initDB =function(){
try{
	if(!window.openDatabase){
	alert('Databases are not supported in this device');
	return;
	}
	else{
		//defining global variables
		var shortName = 'database';
		var version ='1.0';
		var displayName = 'property database';
		var maxSize = 65535;
		
		db =window.openDatabase(shortName, version, displayName, maxSize);
		//db.transaction(function (transaction){
		
		document.addEventListener("deviceready", phoneReady, false);
		
		$("#submission_form").live("submit",function(e){
			//if( !$.mobile.ajaxFormsEnabled ){ return; }
			var data  ={prop_name:$("#property_name").val(),
						street : $("#street").val(),
			 			suburb: $("#suburb").val(),
			 			town :$("#town").val(),
			 			district :$("#district").val(),
			 			date : $("#date").val(),
			 			owner_name : $("#owner_name").val(),
			 			introducer : $("#introducer").val()
			 			};
			createtable(data, function(){
				$mobile.changePage("index.html",{reverse:true});
			});
			e.preventDefault();submissionform
		})
			
	
	}
}catch (e){
	// Error handling code goes here. 
	
	alert ("database did'nt created");
    //if (e == INVALID_STATE_ERR) { 

      // Version number mismatch. 
      //alert("Invalid database version.");
      //}
    //else {
    //	alert("Unknown error "+e+"."); 
    //}
    return
   }
  }




//document.addEventListener("deviceready", onDeviceReady, false);
//function onDeviceReady() {
	
//}


//this id called when an error happens in the transaction
function errorHandler (err){
	alert ('Error:' +err.message + 'code:' +err.code);
}

//null db data handler
nullHandler = function (transaction, results){}

function createtable(data,cb){
	try{
		db.transaction(function (transaction){
			transaction.executeSql('CREATE TABLE IF NOT EXISTS Property_detail(property_name TEST NOT NULL, street TEXT, suburb TEXT,town TEXT, district TEXT, date INTEGER, owner_name TEXT, introducer TEXT );', [], nullDataHandler, errorHandler);
			alert ('database is created');
			
			transaction.executeSql("insert into Property_detail(property_name,street,suburb,town, district,date,owner_name,introducer) VALUES (?,?,?,?,?,?,?,?)", [property_detail.property_name, property_detail.street, property_detail.suburb, property_detail.town, property_detail.district, property_detail.date, property_detail.woner_name, property_detail.introducer]), nullDataHandler, errorHandler}, 
			//console.log('db created');
			//alert ('your data is updated');
		cb);
	}catch(e){
		alert ("couldn't create the database");
		return;
	}
}


// callback function to retrieve the data from the property_detail table

celebsDataHandler=function(transaction, results) {

  // Handle the results 

  var html = "<ul>"; 

  for (var i=0; i<results.rows.length; i++) { 

    var row = results.rows.item(i); 

    html += '<li>'+row['name']+'</li>\n';

  } 

  html +='</ul>';

  alert(html);

}





// load the currently selected icons

loadCelebs = function() {

  try {



    mydb.transaction(

        function(transaction) {

           transaction.executeSql('SELECT * FROM property_detail ORDER BY prop_name',[], celebsDataHandler, errorHandler);

        });


  } catch(e) {

    alert('no data');

  }
} 



/*
//this is calles when a successful transactiion happen
function successCallBack(){
	alert ('DEBUGGING success');
}

//function nullHandler(){}
*/

/*
if(!winodw.openDatabase){
	//if  not device not support the database
	alert('Databases are not supported in this device');
	return;
}

//this will open the database locally on the device
//if does not exist, it will create it & return a database object stored in variable db

//this line will try to create the table property_detail in the database just created/opened 
db.transaction(function(tx){

	
	//this line creates the table property_detail if it does not exist & 
	//sets up the columns prop_id,prop_name,prospective or not, street, suburb ,town, district, date, owner's name, introducer if available.
	//prop_is column is an auto incrementing column.
	tx.executeSql('CREATE TABLE IF NOT EXISTS Property_detail(prop_id INTEGER NOT NULL PRIMARY KEY,property_name TEST NOT NULL, street TEXT, suburb TEXT, district TEXT, date INTEGER, owner_name TEXT, introducer TEXT )',[],nullHandler,errorHandler);
	},errorHandler,successCallBack); 
} 		
/*
//list the values in the database to the screen using jquery to update the #lbprop element
function ListDBValues(){
if (!winodow.openDatabase){
	alert('Databases are not supported in this deivice');
	}
}
//this line clears out any content in the #lbprop element on the page so that the next few lines will show updated content and not just keep repeating lines 
 $('#lbprop').html('');
 
 //this next section will select all the content from the propert_detail table and then go through it row by row 
 //appending the prop_id,prop_name,prospective or not, street, suburb ,town, district, date, owner's name, introducer to the  #lbprop element on the page 
  db.transaction(function(transaction) { 
    transaction.executeSql('SELECT * FROM prop_detail;', [], 
      function(transaction, result) { 
       if (result != null && result.rows != null) { 
         for (var i = 0; i < result.rows.length; i++) { 
           var row = result.rows.item(i); 
           $('#lbprop').append('<br>' + row.UserId + '. ' + 
 row.FirstName+ ' ' + row.LastName); 
         } 
       } 
      },errorHandler); 
  },errorHandler,nullHandler); 


  return; 
 } 

 
//this is the function that puts values into the database using the values from the text boxes on the screen 
function AddValueToDB(){ 

 if (!window.openDatabase) { 
   alert('Databases are not supported in this browser.'); 
   return; 
 } 
// this is the section that actually inserts the values into the User table 
 db.transaction(function(transaction) { 
   transaction.executeSql('INSERT INTO Property_detail(prop_id, property_name,street,suburb,district,date,owner_name,introducer) VALUES (?,?,?,?,?,?,?,?)',[$('#txprop_name').val(), $('#txprop_name').val(), $('#txstreet').val(),$('#txsuburb').val(),$('#txdistrict').val(),$('#txdate').val(),$('#txowner_name').val(),$('#txintroducer').val()],nullHandler,errorHandler); 
 });                                                                                         

// this calls the function that will show what is in the User table in the database 
 //ListDBValues(); 
 return false; 
}
*/
